package com.LeeCode;

import java.util.Arrays;

/**
 * 连续的子数组和
 */

public class Code523 {
    public static void main(String[] args) {
        int[] nums = {23, 2, 4, 6, 7};
        int k = 6;
        System.out.println(new Code523().checkSubarraySum(nums, k));
    }

    public boolean checkSubarraySum(int[] nums, int k) {
        // 特殊情况处理
        if (nums.length < 2) {
            return false;
        }

        int[] cnt = new int[k];
        Arrays.fill(cnt, -2);
        cnt[0] = -1;

        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];

            sum %= k;

            if (cnt[sum] > -2) {
                // 检查长度是否至少为2
                if (i - cnt[sum] > 1) {
                    return true;
                }
            } else {
                cnt[sum] = i;
            }
        }

        return false;
    }
}
